import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  Input,
  OnDestroy,
  ViewEncapsulation,
} from '@angular/core'
import {
  GuardsCheckEnd,
  GuardsCheckStart,
  NavigationCancel,
  NavigationError,
  Router,
} from '@angular/router'

@Component({
  selector: 'ad-route-loading',
  template: `
    <div class="ad-route-loading-preloader" *ngIf="isLoadingGuard">
      <div class="ad-route-loading-spinner">
        <div class="ad-route-loading-double-bounce1"></div>
        <div class="ad-route-loading-double-bounce2"></div>
      </div>
    </div>
  `,
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: 'ad-route-loading',
  },
})
export class AdRouteLoadingComponent implements OnDestroy {
  public isLoadingGuard = false
  @Input() public backgroundColor = 'rgba(0, 115, 170, 0.69)'

  constructor(private router: Router, private cd: ChangeDetectorRef) {
    this.router.events.subscribe(
      (event) => {
        if (event instanceof GuardsCheckStart) {
          this.isLoadingGuard = true
          this.cd.detectChanges()
        } else if (
          event instanceof GuardsCheckEnd ||
          event instanceof NavigationCancel ||
          event instanceof NavigationError
        ) {
          this.isLoadingGuard = false
          this.cd.detectChanges()
        }
      },
      () => {
        this.isLoadingGuard = false
        this.cd.detectChanges()
      }
    )
  }

  ngOnDestroy(): void {
    this.isLoadingGuard = false
    this.cd.detectChanges()
  }
}
